import mmap
import pickle
from multiprocessing import shared_memory

SHM_VIDEO_NAME="FishVideo"

def CreateSharedMemory(shname):
    # Sample dictionary to store in shared memory
    my_dict = {'VideoID':-1, 'VideoFile': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.mp4'}

    # Serialize the dictionary to bytes using pickle
    dict_bytes = pickle.dumps(my_dict)

    # Create shared memory block with a name (e.g., 'my_shared_memory') and size of the serialized dictionary
    shm = shared_memory.SharedMemory(name=shname, create=True, size=len(dict_bytes) * 2)

    # Write the serialized dictionary bytes to the shared memory
    shm.buf[:len(dict_bytes)] = dict_bytes

    print(f"Shared memory created with name: {shm.name} and size: {len(dict_bytes)} bytes")

    return shm

def LoadGlobalDict(shm_name):
    shm = shared_memory.SharedMemory(name=shm_name)

    # Read the serialized dictionary from shared memory
    serialized_dict = bytes(shm.buf[:])

    # Deserialize the dictionary
    dict_data = pickle.loads(serialized_dict)

    print("Dictionary loaded from shared memory:", dict_data)

    # Close shared memory after reading
    # shm.close()

    return dict_data

def StoreGlobalDict(shm_name, dict):
    # Serialize the dictionary using pickle
    serialized_dict = pickle.dumps(dict)

    # Create shared memory for the serialized dictionary
    shm = shared_memory.SharedMemory(name=shm_name)

    # Write the serialized dictionary to shared memory
    buffer = memoryview(shm.buf)
    buffer[:len(serialized_dict)] = serialized_dict

    del buffer

    print(f"Dictionary stored in shared memory with name {shm.name}")
